package io.renren.modules.generator.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.modules.generator.entity.CommodityEntity;
import io.renren.modules.generator.entity.CouponEntity;
import io.renren.modules.generator.service.CommodityService;
import io.renren.modules.generator.service.CouponService;
import io.renren.modules.generator.vo.InformationVo;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.InformationDao;
import io.renren.modules.generator.entity.InformationEntity;
import io.renren.modules.generator.service.InformationService;


@Service("informationService")
public class InformationServiceImpl extends ServiceImpl<InformationDao, InformationEntity> implements InformationService {

    @Autowired
    CommodityService commodityService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    CouponService couponService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InformationEntity> page = this.page(
                new Query<InformationEntity>().getPage(params),
                new QueryWrapper<InformationEntity>()
                        .orderByDesc("create_time")
        );

        return new PageUtils(page);
    }

    @Override
    public String addOrder(InformationVo informationVo) {
        Map<String, Integer> commodityMap = informationVo.getCommodityMap();
        Long userId = informationVo.getUserId();
        Long currentUserId = informationVo.getCurrentUserId();
        Integer couponId = informationVo.getCouponId();
        Float realPrice = informationVo.getRealPrice();
        String uuid = UUID.randomUUID().toString().replace("-","");
        for (String commodityId : commodityMap.keySet()) {
            InformationEntity informationEntity = new InformationEntity();
            Integer num = commodityMap.get(commodityId);
            CommodityEntity commodity = commodityService.getById(commodityId);
            Float commodityPrice = commodity.getCommodityPrice();
            Float commodityDiscount = Float.valueOf(commodity.getCommodityDiscount());
            informationEntity.setCommodityId(commodityId);
            informationEntity.setNumber(num);
            informationEntity.setPrice(commodityPrice*num*commodityDiscount);
            informationEntity.setRealPrice(realPrice);
            informationEntity.setCouponId(couponId);
            informationEntity.setUserId(userId);
            informationEntity.setCurrentUserId(currentUserId);
            informationEntity.setInformationId(uuid);
            this.save(informationEntity);
        }

        // 返回订单id
        return uuid;
    }

    @Override
    public PageUtils queryInformationByUserId(Map<String, Object> params) {
        Long userId = Long.parseLong((String) params.get("userId"));
        QueryWrapper<InformationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<InformationEntity> informationEntities = this.list(queryWrapper);

        Map<String, InformationVo> voHashMap = new HashMap<>();
        for (InformationEntity informationEntity : informationEntities) {
            String informationId = informationEntity.getInformationId();
            InformationVo informationVo = voHashMap.getOrDefault(informationId, new InformationVo());
            Map<String, Integer> commodityMap = informationVo.getCommodityMap();
            if (commodityMap == null) {
                commodityMap = new HashMap<>();
            }
            CommodityEntity commodity = commodityService.getById(informationEntity.getCommodityId());
            commodityMap.put(informationEntity.getCommodityId(), informationEntity.getNumber());
            informationVo.setCommodityMap(commodityMap);
            informationVo.setInformationId(informationId);
            informationVo.setUserId(userId);
            informationVo.setCurrentUserId(informationEntity.getCurrentUserId());
            informationVo.setGrade(informationEntity.getGrade());
            informationVo.setStatus(informationEntity.getStatus());
            informationVo.setPrice(informationEntity.getPrice());
            informationVo.setRealPrice(informationEntity.getRealPrice());
            informationVo.setCommodityEntity(commodity);
            informationVo.setCreateTime(informationEntity.getCreateTime());

            voHashMap.put(informationId, informationVo);
        }

        List<InformationVo> informationVos = new ArrayList<>();
        for (String informationId : voHashMap.keySet()) {
            informationVos.add(voHashMap.get(informationId));
        }
        Collections.sort(informationVos, (o1, o2) -> {
            if (o1.getCreateTime().before(o2.getCreateTime())) {
                return 1;
            } else {
                return -1;
            }
        });
        Page<InformationVo> pg = new Page<>();
        pg.setRecords(informationVos);
        return new PageUtils(informationVos, informationVos.size(), Integer.parseInt((String) params.get("limit")), Integer.parseInt((String) params.get("page")));
    }

    @Override
    public Boolean gradeOrder(InformationVo informationVo) {
        List<InformationEntity> list = this.list(new QueryWrapper<InformationEntity>().eq("information_id", informationVo.getInformationId()));
        for (InformationEntity informationEntity : list) {
            informationEntity.setGrade(informationVo.getGrade());
        }
        this.updateBatchById(list);
        List<InformationEntity> currentUserId = this.list(new QueryWrapper<InformationEntity>().eq("current_user_id", informationVo.getCurrentUserId()));
        int count = 0;
        int totalPoints = 0;
        for (InformationEntity informationEntity : currentUserId) {
            count++;
            totalPoints += informationEntity.getGrade();
        }
        SysUserEntity currentUser = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", informationVo.getCurrentUserId()));
        currentUser.setGrade(totalPoints/count);
        return sysUserService.updateById(currentUser);
    }

    @Override
    public Boolean changeInformation(InformationVo informationVo) {
        List<InformationEntity> list = this.list(new QueryWrapper<InformationEntity>().eq("information_id", informationVo.getInformationId()));
        for (InformationEntity informationEntity : list) {
            informationEntity.setStatus(informationVo.getStatus());
            Integer couponId = informationVo.getCouponId();
            if (couponId != null) {
                informationEntity.setCouponId(couponId);
                CouponEntity coupon = couponService.getById(couponId);
                informationEntity.setRealPrice(informationEntity.getPrice()-coupon.getPreferentialPrice());
            }
            if (informationVo.getCurrentUserId() != null) {
                informationEntity.setCurrentUserId(informationVo.getCurrentUserId());
            }
        }
        return this.updateBatchById(list);
    }
}